package signHelper.dao;

import java.util.List;

import org.springframework.dao.support.DataAccessUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;


/**
 * 
 * @author <a href="mailto:1360527082@qq.com">王焕</a>
 * @since 0.1.0
 */
public class JdbcHelper {

	public static SqlParameterSource getSqlParameterSource(Object object) {
		if (object != null)
			return new BeanPropertySqlParameterSource(object);
		return null;
	}

	public static <T> RowMapper<T> getRowMapper(Class<T> mappedClass) {
		RowMapper<T> rowMapper = BeanPropertyRowMapper.newInstance(mappedClass);
		return rowMapper;
	}

	public static <T> Integer insertAndGetKey(NamedParameterJdbcTemplate namedParameterJdbcTemplate, String sql, T t) {
		KeyHolder keyHolder = new GeneratedKeyHolder();
		namedParameterJdbcTemplate.update(sql, JdbcHelper.getSqlParameterSource(t), keyHolder);
		return keyHolder.getKey().intValue();
	}

	public static <T> T queryForObject(JdbcTemplate jdbcTemplate, String sql, RowMapper<T> rm, Object... args) {
		List<T> results = jdbcTemplate.query(sql, args, rm);
		return results.isEmpty() ? null : DataAccessUtils.requiredSingleResult(results);
	}
}
